package com.zm.openapi.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by songxl on 2018/10/19.
 */
@Slf4j
public class WebfluxHttpUtil {

    public static Map<String, Object> decodeBody(String body) {
        body = StringUtils.trim(body);
        if (StringUtils.isBlank(body) || "{}".equals(body) || "[]".equals(body))
            return new LinkedHashMap<>();
        return Arrays.stream(body.split("&"))
                .map(s -> s.split("="))
                .collect(Collectors.toMap(arr -> arr[0], arr -> arr[1]));
    }

    public static String encodeBody(Map<String, Object> map) {
        if (MapUtils.isEmpty(map))
            return StringUtils.EMPTY;

        return map.entrySet()
                .stream()
                .map(e -> e.getKey() + "=" + (e.getValue() == null ? "" : e.getValue()))
                .collect(Collectors.joining("&"));
    }

}
